# coding=utf-8
import logging
from datetime import datetime, timedelta, date
from common.utils.decorator import sql_wrapper
from common.utils.db import list_object, get, upsert, list_export_object, generate_filter
from common.order_withdraw.model import OrderWithdraw
from common.card_statistics_monthly.model import CardStatisticsMonthly
from common.card_statistics_monthly import handler as helper
from common.utils import id_generator
from common.utils import exceptions as err
from common import orm
from sqlalchemy import func, Date, cast
from common.utils.types import Enum
from decimal import Decimal

_LOGGER = logging.getLogger('hydra')


@sql_wrapper
def get_cards_statistics(card_code):
    monthly = CardStatisticsMonthly.query.filter(CardStatisticsMonthly.card_code == card_code,
                                                 cast(CardStatisticsMonthly.created_at, Date) == date.today()).first()
    if not monthly:
        monthly = CardStatisticsMonthly()

    return monthly


@sql_wrapper
def upsert_card_statistics(card_code, order_amount, order_status=-1, reverse=False):
    days_of_month = helper.get_day_of_week()
    monthly = {}
    for x in days_of_month:
        monthly = CardStatisticsMonthly.query.filter(CardStatisticsMonthly.card_code == card_code,
                                                     cast(CardStatisticsMonthly.created_at, Date) == x).first()
        if monthly:
            break

    if order_status == -1:
        if not monthly:
            monthly = CardStatisticsMonthly()
            monthly.created_at = datetime.utcnow()
            monthly.card_code = card_code

        amount = Decimal(order_amount if not reverse else -order_amount)
        count = 1 if not reverse else 1
        monthly.total_amount += amount
        monthly.payment_amount += amount
        monthly.processing_amount += amount
        monthly.total_count += count
        monthly.payment_count += count
        monthly.processing_count += count
        monthly.updated_at = datetime.utcnow()
        monthly.save()
    else:
        if monthly:
            monthly.processing_amount -= order_amount;
            monthly.processing_count -= 1

            if order_status == 2:  # ORDER_STATUS.SUCCESS:
                monthly.auto_close_amount += order_amount;
                monthly.auto_close_count += 1
            elif order_status == 3:  # ORDER_STATUS.MANUALSUCCESS:
                monthly.manual_close_amount += order_amount
                monthly.manual_close_count += 1
            elif order_status == 4:  # ORDER_STATUS.INVALID:
                monthly.invalid_amount += order_amount
                monthly.invalid_count += 1
            monthly.updated_at = datetime.utcnow()
            monthly.save()
